<template>
  <div class="gas-price-container">
    <div class="page-title">
      <div>气费定价管理</div>
    </div>
    <el-card class="system-card">
      <template #header>
        <el-input
          clearable
          v-model="searchName"
          style="width: 150px"
          placeholder="搜索用气类别"
          @input="handleSearch"
        ></el-input>
        <el-button
          icon="plus"
          size="small"
          type="primary"
          @click="handleAdd"
          :disabled="hasEditingRow"
        >
          添加定价方案
        </el-button>
      </template>

      <!-- 价格方案展示表格 -->
      <el-table
        :data="gasPrices"
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column align="center" prop="name" label="用气类别">
          <template #default="{ row }">
            <div v-if="row.isEditing || row.isNew">
              <el-input
                v-model="row.name"
                placeholder="请输入用气类别"
                @blur="handleNameBlur(row)"
                @keyup.enter="handleSave(row)"
              />
            </div>
            <div v-else>
              {{ row.name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="价格(元/吨)">
          <template #default="{ row }">
            <div v-if="row.isEditing || row.isNew">
              <el-input-number
                v-model="row.tempPrice"
                :precision="2"
                :step="0.1"
                :min="0"
                :max="999"
                style="width: 100%"
                @keyup.enter="handleSave(row)"
              />
            </div>
            <div v-else>
              {{ row.fixed_price }}
            </div>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template #default="scope">
            <div v-if="scope.row.isEditing || scope.row.isNew">
              <el-button
                size="small"
                type="success"
                @click="handleSave(scope.row)"
              >
                保存
              </el-button>
              <el-button size="small" @click="handleCancel(scope.row)">
                取消
              </el-button>
            </div>
            <div v-else>
              <el-button
                size="small"
                type="primary"
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import {
  getPricesApi,
  createPriceApi,
  updatePriceApi,
  deletePriceApi,
} from "@/api/price";
import { useCompanyStore } from "@/stores/company";
import { debounce } from "@/utils/DebounceAndThrottle";
import { ref, watch, computed } from "vue";

const companyStore = useCompanyStore();
const gasPrices = ref([]);
const loading = ref(false);
const searchName = ref("");

// 判断是否有正在编辑的行
const hasEditingRow = computed(() => {
  return gasPrices.value.some((row) => row.isEditing || row.isNew);
});

// 获取价格列表
async function fetchGasPrice() {
  loading.value = true;
  try {
    let res = await getPricesApi({
      type: 1,
      company_id: companyStore.currentCompany.id,
      name: searchName.value ? `%${searchName.value}%` : undefined,
    });
    gasPrices.value = res.data;
  } catch (error) {
    ElMessage.error("获取价格失败");
  } finally {
    loading.value = false;
  }
}

// 处理搜索
const handleSearch = debounce(fetchGasPrice, 500);

// 处理添加按钮点击
const handleAdd = () => {
  const newRow = {
    name: "",
    fixed_price: 0,
    tempPrice: 0,
    isNew: true,
    company_id: companyStore.currentCompany.id,
    price_mode: "固定价格",
    type: 1,
    originalData: null, // 用于存储原始数据
  };
  gasPrices.value.unshift(newRow);
};

// 处理名称失去焦点
const handleNameBlur = (row) => {
  if (!row.name && row.isNew) {
    gasPrices.value = gasPrices.value.filter((item) => item !== row);
  }
};

// 处理编辑按钮点击
const handleEdit = (row) => {
  // 保存原始数据
  row.originalData = {
    name: row.name,
    fixed_price: row.fixed_price,
  };
  row.isEditing = true;
  row.tempPrice = row.fixed_price;
};

// 处理取消按钮点击
const handleCancel = (row) => {
  if (row.isNew) {
    // 如果是新添加的行，直接移除
    gasPrices.value = gasPrices.value.filter((item) => item !== row);
  } else {
    // 恢复原始数据
    row.name = row.originalData.name;
    row.tempPrice = row.originalData.fixed_price;
    row.isEditing = false;
  }
};

// 处理保存按钮点击
const handleSave = async (row) => {
  if (!row.name) {
    ElMessage.warning("请输入用气类别");
    return;
  }

  if (row.isNew) {
    row.fixed_price = row.tempPrice || 0;
  } else if (row.tempPrice == row.fixed_price) {
    ElMessage.info("价格未修改");
    row.isEditing = false;
    return;
  }

  loading.value = true;
  let data = {
    ...(row.isNew
      ? {
          name: row.name,
          company_id: row.company_id,
          price_mode: row.price_mode,
          type: row.type,
          fixed_price: row.tempPrice || 0,
        }
      : {
          id: row.id,
          fixed_price: row.tempPrice,
        }),
  };
  try {
    if (row.isNew) {
      await createPriceApi(data);
    } else {
      await updatePriceApi(data);
    }
    await fetchGasPrice();
    ElMessage.success(row.isNew ? "添加成功" : "修改成功");
  } catch (error) {
    ElMessage.error(row.isNew ? "添加失败" : "保存失败");
  } finally {
    row.isEditing = false;
    row.isNew = false;
    loading.value = false;
    row.originalData = null; // 清除原始数据
  }
};

// 处理删除按钮点击
const handleDelete = async (row) => {
  if (row.isNew) {
    gasPrices.value = gasPrices.value.filter((item) => item !== row);
    return;
  }

  try {
    await ElMessageBox.confirm("确定要删除该价格方案吗？", "提示", {
      type: "warning",
    });

    loading.value = true;
    await deletePriceApi({ id: "" + row.id });
    ElMessage.success("删除成功");
    await fetchGasPrice();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  } finally {
    loading.value = false;
  }
};

// 监听公司变化
watch(
  () => companyStore.currentCompany,
  async () => {
    await fetchGasPrice();
  },
  {
    immediate: true,
  }
);
</script>

<style scoped>
.gas-price-container {
  padding: 20px;
}

.system-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  color: var(--el-text-color-primary);
}
</style>
